/**
 * @file 支付看板
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-01-19
 */
import React, {Fragment, useState, useEffect} from 'react';
import {Space, Card, Input, Row, Col} from 'antd';

import moment from 'moment';

import {
    getResult,
    fetchSearchFormOptions
} from '~/service/shortPeriod';

import {getFirstAndLastTimestamp} from '~/utils/date';
import {numberHandle, parsePercent} from '~/utils/number';
import {convertChartListToMap} from '../../../utils/convert';

import CommonSearchBar from '../../../common/CommonSearchBar';
import EchartsLineCard from '../../../common/EchartsLineCard';
import CommonTitle from '../../../common/Title';

import {formatTooltip} from '../../../utils/formatTooltip';
import {searchForm, getDimensionId, pageId, PartType, META} from './config';

const {TextArea} = Input;

const initialValues = {
    startClassTime: getFirstAndLastTimestamp({format: 'YYYY-MM-DD'})
};


const PartFour = props => {
    const {onDetail, onDownLoad} = props;

    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState({});
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    const [drilingList, setDrilingList] = useState([]);
    const [drilingLevel, setDrilingLevel] = useState(null);

    const {
        allUnitType: {
            compositeUnit = [],
            textList = []
        } = {}
    } = result;

    const partThreeComposite = convertChartListToMap(compositeUnit);
    const partThreeText = convertChartListToMap(textList);

    const {
        [META.PART_THREE_COMPOSITE_ONE]: partThreeCompositeOne,
    } = partThreeComposite;

    const {
        [META.PART_THREE_TEXT_ONE]: partThreeTextOne
    } = partThreeText;

    // 获取全局数据
    const getData = (params = searchFormValues) => {
        setLoading(true);

        const {startClassTime} = params;
        const [begin, end] = startClassTime || [];
        const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
        const endRangeTime = end && moment(end).format('YYYY-MM-DD');
        params.beginDay = [beginRangeTime, endRangeTime];
        params.part = PartType;

        getResult(params)
            .then(res => {
                const {
                    data
                } = res;

                setResult(data);
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const handleDetail = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList,
            part: PartType
        };

        onDetail(params);
    };

    const handleDownload = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList,
            part: PartType
        };

        onDownLoad(params);
    };

    const handleBack = async params => {
        console.log('返回', params);
        const {unitId, unitName} = params;
        // 所有下钻取消
        setDrilingList([]);

        try {
            await getData(searchFormValues);
            // 返回搜索数据接口调用成功后level - 1
            setDrilingLevel({unitId, level: 0});
        }
        catch {}
    };

    const handleDrilling = async params => {
        console.log('下钻', params);
        const {unitId, unitName, info, dimension = {}} = params;

        const driling = {
            unitId,
            unitName,
            value: info.name,
            ...dimension
        };

        setDrilingList([driling]);

        try {
            await getData({...searchFormValues, drilingList: [driling]});
            // 搜索接口调用成功后level + 1
            setDrilingLevel({unitId, level: 1});
        }
        catch {}
    };

    useEffect(() => {
        getData();
    }, []);

    // 表单确定
    const handleOk = fieldsValue => {
        setSearchFormValues(fieldsValue);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(fieldsValue);
    };

    // 表单重置
    const handleReset = e => {
        setSearchFormValues(initialValues);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(initialValues);
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        // setSearchFormValues({...searchFormValues, ...itemKeyValue});
        console.log('handleItemChange', itemKeyValue);
    };

    // 请求单个表单配置项
    const handleFetchOptions = (
        {key, searchKey, pager, dependItemKey, dependItemValue, isGetingMore, options: curOptions, fieldsValue}
    ) => {
        let permissions = searchForm.map(item => {
            if (item.key === 'startClassTime') {
                const [begin, end] = fieldsValue[item.key] || [];
                const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
                const endRangeTime = end && moment(end).format('YYYY-MM-DD');
                const filterItems = [beginRangeTime, endRangeTime];
                const dimensionId = getDimensionId(0, 'beginDay');

                return (
                    {
                        dimensionId,
                        dimensionName: 'beginDay',
                        filterItems
                    }
                );
            }
            return (
                {
                    dimensionId: getDimensionId(0, item.key),
                    dimensionName: item.key,
                    filterItems: fieldsValue[item.key]
                }
            );
        });

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: getDimensionId(0, key),
            dimensionName: key,
            searchKey,
            permissions,
            unitId: pageId[0].selectID
        };

        fetchSearchFormOptions(params)
            .then(res => {
                const {data, pager} = res;

                let options = data.map(item => (
                    {
                        key: item,
                        value: item,
                        label: item
                    }
                )) || [];

                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }

                setSelectOptions({key, options, pager});
            });
    };

    return (
        <div>
            <CommonTitle
                type="subTitle"
                title="四、训练营转化情况"
            />
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    loading={loading}
                    noCache
                    config={searchForm}
                    initialValues={initialValues}
                    onOk={handleOk}
                    onReset={handleReset}
                    onItemChange={handleItemChange}
                    onfetchOptions={handleFetchOptions}
                    selectOptions={selectOptions}
                />
            </Card>
            <Card style={{width: '100%'}}>
                <Row>
                    <EchartsLineCard
                        id={META.PART_THREE_COMPOSITE_ONE}
                        key={META.PART_THREE_COMPOSITE_ONE}
                        data={partThreeCompositeOne}
                        loading={loading}
                        span={20}
                        title={partThreeCompositeOne?.unitName ?? ''}
                        onBack={handleBack}
                        onDownload={handleDownload}
                        onDetail={handleDetail}
                        onDrilling={handleDrilling}
                        drilingLevel={drilingLevel}
                        grid={{left: '8%', right: '8%', bottom: 100}}
                        yAxisIndex={1}
                        // label={{
                        //     line: params => `${numberHandle(params.data.value, 2)}`,
                        //     bar: params => `${numberHandle(params.data.value, 2)}`
                        // }}
                        smooth
                        tooltip={(params => formatTooltip(params))}
                    />
                    <Col span={4}>
                        <TextArea
                            className="short-period-text-area"
                            style={{height: 435}}
                            value={partThreeTextOne?.textContent}
                            bordered={false}
                            readOnly
                        />
                    </Col>
                </Row>
            </Card>
        </div>
    );
};

export default PartFour;
